package com.hulk.ratel.test;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import fi.iki.elonen.NanoHTTPD;
import lombok.extern.slf4j.Slf4j;


//参考：https://www.cnblogs.com/exmyth/p/7524432.html

@Slf4j
public class App extends NanoHTTPD {

    public App() throws IOException {
        super(19083);
        start(NanoHTTPD.SOCKET_READ_TIMEOUT, false);
        System.out.println("\nRunning! Point your browsers to http://localhost:19083/ \n");
    }

    public static void main(String[] args) {
        try {
            new App();
        } catch (IOException ioe) {
            System.err.println("Couldn't start server:\n" + ioe);
        }
    }

    @Override
    public Response serve(IHTTPSession session) {
        Method method = session.getMethod();
        log.info("Method", method.toString());

        if (NanoHTTPD.Method.POST.equals(method)) {
            Map<String, String> files = new HashMap<String, String>();
                 /*获取header信息，NanoHttp的header不仅仅是HTTP的header，还包括其他信息。*/
            Map<String, String> header = session.getHeaders();

            try {
                session.parseBody(files);
                String param = files.get("postData");

                log.info("header : " + header);
                log.info("files : " + files);
                log.info("json : " + param);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            log.error("测试方法不支持");
        }

        //return super.serve(session);
        return newFixedLengthResponse(Response.Status.OK, NanoHTTPD.MIME_PLAINTEXT, "000000");
    }
}
